package com.asyf.provider.common.config;

import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author HelloWoodes
 */
//@Configuration
public class DataSourceProxyConfig {

    @Bean("primary")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource dataSourceMaster() {
        return DataSourceBuilder.create().build();
    }

    @Bean("secondary")
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource dataSourceStorage() {
        return DataSourceBuilder.create().build();
    }

    //配置数据源代理，支持自动和手动两种配
    @Bean(name = "primaryProxy")
    public DataSourceProxy masterDataSourceProxy(@Qualifier("primary") DataSource dataSource) {
        return new DataSourceProxy(dataSource);
    }

    @Bean(name = "secondaryProxy")
    public DataSourceProxy storageDataSourceProxy(@Qualifier("secondary") DataSource dataSource) {
        return new DataSourceProxy(dataSource);
    }

    @Bean("dynamicDataSource")
    public DataSource dynamicDataSource(@Qualifier("primaryProxy") DataSource primaryProxy,
                                        @Qualifier("secondaryProxy") DataSource secondaryProxy) {

        DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource();

        Map<Object, Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put(DataSourceKey.PRIMARY.name(), primaryProxy);
        dataSourceMap.put(DataSourceKey.SECONDARY.name(), secondaryProxy);

        dynamicRoutingDataSource.setDefaultTargetDataSource(primaryProxy);
        dynamicRoutingDataSource.setTargetDataSources(dataSourceMap);

        DynamicDataSourceContextHolder.getDataSourceKeys().addAll(dataSourceMap.keySet());
        return dynamicRoutingDataSource;
    }

    @Bean(name = "namedParameterJdbcTemplate")
    @Primary
    public NamedParameterJdbcTemplate namedParameterJdbcTemplate(@Qualifier("dynamicDataSource") DataSource dataSource) {
        return new NamedParameterJdbcTemplate(dataSource);
    }

}